# -*- coding: utf-8 -*- 
import cgi
import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from thinkmodel import Propos,ProposSimilar
  
"""
main page
"""
class MainPage(webapp.RequestHandler):
  def get(self):
    #add recent add propose
    query = Propos.all()
    items = query.order('-modifydate').fetch(10)
    template_values = {
      'items':items,}
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    print path
    self.response.out.write(template.render(path, template_values))

"""
show result of a query by key word
post method only
"""
class Search(webapp.RequestHandler):
  def post(self):
    gc = self.request.get('content')
    ppquery = Propos.all()
    result = []

    for pp in ppquery:
      if pp.content.find(gc) != -1:
        result.append(pp)
    
    template_values = {
      'items':result,
      'searchword':gc,
      }
    path = os.path.join(os.path.dirname(__file__), 'searchresult.html')
    self.response.out.write(template.render(path, template_values))

"""
create link between two exist item
"""
class CreateLink(webapp.RequestHandler):
  def get(self):
    childkey = self.request.get('childkey')
    parentkey = self.request.get('parentkey')
    pentity = db.get(parentkey)
    centity = db.get(childkey)
    #set children
    pentity.subpropos.append(centity.key())
    pentity.put()
    #set parent
    centity.parentpropos.append(pentity.key())
    centity.put()
    
    resultstr = ""
    resultstr += pentity.content
    resultstr += " is the parent of "
    resultstr += centity.content
    self.response.out.write("create link ok<br/>"+resultstr)

"""
add a propose
get show the add page
post add to database
"""
class Add(webapp.RequestHandler):
  def post(self):
    self.response.out.write('<html><body>')
    #print self.request.get('addcontent')
    if self.request.get('addcontent') != "":
      pp = Propos(content=self.request.get('addcontent'))
      pp.put()
      pp.updateSimilar()
      self.response.out.write("add ok"+pp.content)
			
    self.response.out.write("""<center><a href="/">return to home</a></center></body></html>""")
    #how to self redirect

  def get(self):
    template_values={}
    path = os.path.join(os.path.dirname(__file__), 'add.html')
    self.response.out.write(template.render(path, template_values))

"""
show a propos tree
get method only
need change show the parents of an item
"""
class Show(webapp.RequestHandler):
  def post(self):
    self.response.out.write("to be continue")
    
  def get(self):
    """
      reverse output the tree structure
    """
    keystr = self.request.get('qkey')
    entity = db.get(keystr)

    parentstr = "<hr/><ul><h2>parent list:</h2>"
    for pitem in entity.parentpropos:
      try:
        pentity = db.get(pitem)
        parentstr += ("<li><a href=\"show?qkey="+str(pitem)+"\">"+pentity.content+"</a></li>")
      except:
        entity.parentpropos.remove(pitem)
        parentstr += "repair db"+str(pitem)
    parentstr += "</ul>"
    
    returnhomestr = """<br /><a href="/">return to home</a>"""

    if len(entity.parentpropos) == 0:
      self.response.out.write(Show.propos2str(self,entity) + returnhomestr)
    else:
      self.response.out.write(Show.propos2str(self,entity) + parentstr + returnhomestr)      

  def propos2str(self,pp):
    """
      transfer a propose to html source code
    """
    otheroperation = ""
    otheroperation += " <a href = \"/addchild?qkey="+str(pp.key())+"\">addchild</a> "
    otheroperation += "<a href = \"/delete?qkey="+str(pp.key())+"\">delete</a> "
    otheroperation += "<a href = \"/modify?qkey="+str(pp.key())+"\">modify</a> "    
    result = "<li>"
    result += (pp.content+otheroperation)
    result += "<ul>"
    for keyitem in pp.subpropos:
      tempentity = db.get(keyitem)
      if tempentity == None:
        pp.subpropos.remove(keyitem)
        pp.put()
      else:
        result += Show.propos2str(self,tempentity)
    result += "</ul>"
    result += "</li>"
                            
    return result

"""
delete an item
"""
class Delete(webapp.RequestHandler):
  def get(self):
    keystr = self.request.get('qkey')
    entity = db.get(keystr)
    entity.deleteallSimilar()
    entity.delete()
    self.response.out.write("""<center><a href="/">return to home</a></center>""")

"""
add child for a propos
get method:show the interface
post method:
"""
class AddChild(webapp.RequestHandler):
  def get(self):
    template_values = {
      'keystr':self.request.get('qkey'),
      }
    path = os.path.join(os.path.dirname(__file__),'addchild.html')
    self.response.out.write(template.render(path,template_values))
    
  def post(self):
    contentstr = self.request.get('childcontent')
    if contentstr == "":
      template_values = {
        'errstr':'content can\'t be empty',
        }
      path = os.path.join(os.path.dirname(__file__),'error.html')
      self.response.out.write(template.render(path,template_values))
    else:
      tempe = Propos(content=contentstr)
      #a bug about the sequence
      #add and delete has some common function to extract
      tempe.put()
      #modify need to update too
      tempe.updateSimilar()
      
      pkey = self.request.get('parentkey')
      pe = db.get(pkey)
      #update children 
      pe.subpropos.append(tempe.key())
      db.put(pe)
      #update parent
      tempe.parentpropos.append(pe.key())
      tempe.put()
      
      self.response.out.write("""addok<center><a href="/">return to home</a></center>""")

"""
not know what is this
"""
class GetResult(webapp.RequestHandler):
  def get(self):
    queryword = self.request.get('query')
    parentkey = self.request.get('parentkey')
    
    ppquery = Propos.all()
    result = []
    for pp in ppquery:
      if pp.content.find(queryword) != -1:
        result.append(pp)

    template_values={
      'searchword':queryword,
      'parentkey':parentkey,
      'items':result,
      }
    path = os.path.join(os.path.dirname(__file__),'addsearchresult.html')
    self.response.out.write(template.render(path,template_values))
    
  def post(self):
    self.response.out.write("""addok<center><a href="/">return to home</a></center>""")    

"""
show most similar propos
"""
class ShowSimilar(webapp.RequestHandler):
  def get(self):
    query = ProposSimilar.all()
    query.order('-simvalue')
    items = query.fetch(10)

    list1=[]
    list2=[]
    for item in items:
      p1 = db.get(item.proposlist[0])
      list1.append(p1)
      p2 = db.get(item.proposlist[1])
      list2.append(p2)
    template_values ={
      'length':range(0,len(items),1),
      'list1':list1,
      'list2':list2,
      }
    resultstr = "<ul>"
    for item in items:
      resultstr += "<li>"
      p1 = db.get(item.proposlist[0])
      resultstr += "<a href=\"/show?qkey="+str(p1.key())+"\">"+p1.content+"</a>&nbsp;&nbsp;"
      p2 = db.get(item.proposlist[1])
      resultstr += "<a href=\"/show?qkey="+str(p2.key())+"\">"+p2.content+"</a>"
      resultstr += "</li>"
    resultstr += "</ul>"
    resultstr += """<a href="/">return to home</a>"""
    
    self.response.out.write(resultstr)
    #path = os.path.join(os.path.dirname(__file__),'showsimilar.html')
    #self.response.out.write(template.render(path,template_values))

"""
modify the content of an propos
need to update all the similarity about this item
"""
class Modify(webapp.RequestHandler):
  def get(self):
    querykey = self.request.get('qkey')
    entity = db.get(querykey)
    content = entity.content
    template_values = {
      'tcontent':content,
      'tkey':querykey,
      }
    path = os.path.join(os.path.dirname(__file__),'modify.html')
    self.response.out.write(template.render(path,template_values))
    
  def post(self):
    tcontent = self.request.get('tcontent')
    tkey = self.request.get('tkey')
    entity = db.get(tkey)
    entity.content = tcontent
    entity.put()
    entity.updateSimilar()
    self.response.out.write("""modify ok <br /> <a href="/">return to home</a>""")

"""
may be no use
not know why 404 error
"""
class UpdateAllParent(webapp.RequestHandler):
  def get(self):
    Propos.fillParent()
    self.response.out.write("ok")

  def post(self):
    Propos.fillParent()
    self.response.out.write("ok")

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/search', Search),
                                      ('/add',Add),
                                      ('/show',Show),
                                      ('/delete',Delete),
                                      ('/addchild',AddChild),
                                      ('/getResult',GetResult),
                                      ('/createchild',CreateLink),
                                      ('/showsimilar',ShowSimilar),
                                      ('/modify',Modify),
                                      ('updateAllParent',UpdateAllParent),],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
